﻿using System.Collections.Generic;
using System.Windows.Browser;
using SilverCrmSoap.CrmSdk;

namespace SilverCrmSoap.Helpers
{
    public class FormHelper
    {
        #region UserPrivilege enum

        public struct UserPrivileges
        {
            public bool CanRead;
            public bool CanUpdate;
            public bool CanCreate;
        }

        public enum UserPrivilege
        {
            Read,
            Update,
            Create
        }


        #endregion

        public static UserPrivileges GetUserPrivilege(string fieldname)
        {
            var result = new UserPrivileges();
            var attribute = (ScriptObject)XrmHelper.XrmPageDataEntityAttributes.Invoke("get", fieldname);
            var priv = (ScriptObject)attribute.Invoke("getUserPrivilege");
            result.CanRead = (bool)priv.GetProperty("canRead");
            result.CanUpdate = (bool)priv.GetProperty("canUpdate");
            result.CanCreate = (bool) priv.GetProperty("canCreate");
            return result;
        }

        public static bool GetUserPrivilege(string fieldname, UserPrivilege requiredPrivilege)
        {
            var attribute = (ScriptObject)XrmHelper.XrmPageDataEntityAttributes.Invoke("get", fieldname);
            var priv = (ScriptObject)attribute.Invoke("getUserPrivilege");
            var strRequiredPrivilege = "can" + requiredPrivilege;
            return (bool)priv.GetProperty(strRequiredPrivilege);
        }

        public static T GetEntityValue<T>(string fieldname, T defaultValue)
        {
            if (XrmHelper.XrmPageDataEntityAttributes == null) return defaultValue;
            var attribute = (ScriptObject)XrmHelper.XrmPageDataEntityAttributes.Invoke("get", fieldname);
            return (T)attribute.Invoke("getValue");
        }

        public static void SetEntityValue<T>(string fieldname, T value)
        {
            if (XrmHelper.XrmPageDataEntityAttributes == null) return;
            var attribute = (ScriptObject)XrmHelper.XrmPageDataEntityAttributes.Invoke("get", fieldname);
            attribute.Invoke("setValue", new object[] { value });
        }
    }
}
